package shape

import (
	"gitee.com/git_public/vfaith/sugar"
	"gitee.com/git_public/vfaith/sugar/typconv"
	"log"
	"time"
)

// Map 页面显示表头
type Map struct {
	store map[string]any
	keys  []string
}

// NewMap 创建一个新的 Map
func NewMap() *Map {
	return &Map{
		store: make(map[string]any),
		keys:  make([]string, 0),
	}
}

func GetDefaultMap(args []*Map) *Map {
	return sugar.GetDefaultArgs(args, func() *Map {
		return NewMap()
	})
}

func (fm *Map) Keys() []string {
	return fm.keys
}

func (fm *Map) Store() map[string]any {
	return fm.store
}

func (fm *Map) Value(key string) any {
	return fm.store[key]
}

func (fm *Map) ValueInt(key string) int {
	v, e := typconv.AnyToInt(fm.store[key])
	if e == nil {
		return v
	} else {
		return 0
	}
}

func (fm *Map) ValueString(key string) string {
	v, e := typconv.AnyToString(fm.store[key])
	if e == nil {
		return v
	} else {
		return ""
	}
}

func (fm *Map) Values() []any {
	result := make([]any, 0)
	for _, val := range fm.store {
		result = append(result, val)
	}
	return result
}

func (fm *Map) Get(key string) (any, bool) {
	value, exists := fm.store[key]
	return value, exists
}

func (fm *Map) Add(key string, val any) bool {
	if _, exists := fm.store[key]; exists {
		log.Printf("Map Add 【%s】已存在", key)
		return false
	}
	fm.keys = append(fm.keys, key)
	fm.store[key] = val
	return true
}

func (fm *Map) Update(key string, val any) bool {
	if _, exists := fm.store[key]; exists {
		fm.store[key] = val
		return true
	} else {
		fm.Add(key, val)
	}
	return false
}

func (fm *Map) Delete(key string) bool {
	if _, exists := fm.store[key]; exists {
		delete(fm.store, key)

		result := (fm.keys)[:0] // 保留底层数组，避免重新分配内存
		for _, fmKey := range fm.keys {
			if fmKey != key {
				result = append(result, fmKey)
			}
		}
		fm.keys = result

		return true
	}
	return false
}

// ExampleUsageMap 示例用法
func ExampleUsageMap() {
	fm := NewMap()

	fm.Add("key1", 1)
	fm.Add("key1", 1)
	fm.Add("key2", 2)
	fm.Get("key1")
	fm.Update("key1", 2)
	fm.Delete("key1")

	fm.Add("key3", []int{1, 2, 3, 4, 5})
	fm.Add("key4", []int{1, 2, 3, 4, 5})
	fm.Add("key5", "string")

	for _, key := range fm.Keys() {
		log.Println(fm.Get(key))
	}

	k := fm.Value("key3")
	log.Println(k)

	for _, v := range k.([]int) {
		log.Printf("for _,v:=range k.([]int) - 【%d】", v)
	}

	var times []time.Time
	times = append(times, time.Now())
	times = append(times, time.Now())
	times = append(times, time.Now())
	fm.Add("key6", times)

	k61 := fm.Value("key6")
	log.Println(k61)

	k63 := k61.([]time.Time)
	log.Println(k63)

	v1 := fm.Values()
	log.Println(v1)

	log.Println("End")
}
